<template>
  <gui-page
    ref="guiPage"
    :customHeader="true"
    :headerClass="['gui-bg-white', 'gui-dark-bg-level-1']"
  >
    <!-- 自定义头部导航 -->
    <template v-slot:gHeader>
      <view
        style="height: 44px"
        class="gui-flex gui-nowrap gui-rows gui-align-items-center gui-bg-white gui-border-b"
      >
        <!-- 使用组件实现返回按钮及返回首页按钮 -->
        <gui-xhs-header-leading
          :home="false"
          @goBack="goBack"
        ></gui-xhs-header-leading>

        <!-- 导航文本此处也可以是其他自定义内容 -->
        <text
          class="gui-h5 gui-blod gui-flex1 gui-ellipsis gui-primary-text xhs-margin-right-20"
        >
          <gui-search
            class="xhs-margin-right-20"
            @clear="searchStr = ''"
            :kwd="searchStr"
            @inputting="inputting"
            @confirm="confirm"
          ></gui-search>
        </text>
      </view>
    </template>

    <template v-slot:gBody>
      <view class="gui-flex1 gui-flex gui-column">
        <view
          id="content-wrap"
          style="
            padding: 0 15rpx;
            display: flex;
            flex-direction: column;
            gap: 32rpx;
            margin-top: 20rpx;
          "
        >
          <view
            v-for="(item, index) in userList"
            :key="index"
            class="gui-list-items"
            @click="goCard(item)"
            style="padding-left: 30rpx"
          >
            <view
              class="gui-list-image gui-relative"
              style="width: 100rpx; height: 100rpx"
            >
              <image
                class="gui-list-image"
                style="width: 100rpx; height: 100rpx; border-radius: 100rpx"
                mode="aspectFill"
                :src="item.userPic"
              ></image>
            </view>
            <view
              class="gui-list-body"
              style="padding: 0; display: flex; align-items: center"
            >
              <view
                class="gui-list-title"
                style="flex: 1; flex-direction: column; text-align: left"
              >
                <view
                  class="gui-list-title-text gui-primary-text"
                  style="width: 100%"
                  >{{ item.nickname }}</view
                >
                <view
                  class="gui-list-body-desc gui-color-gray"
                  style="width: 100%"
                  >{{ item.description }}
                </view>
              </view>
              <text
                v-show="item.userId"
                class="gui-list-title-desc gui-bold gui-text-center"
              >
                <view
                  v-show="item.isFollow"
                  @tap.stop="cancelfollowAuthor(item)"
                  class="gui-button-mini xhs-border-radius50 xhs-border-gray"
                  style="width: 150rpx; margin-right: 20rpx; text-align: center"
                >
                  <text class="gui-icons xhs-font24">取消关注</text>
                </view>
                <view
                  v-show="!item.isFollow"
                  @tap.stop="followAuthor(item)"
                  type="default"
                  class="gui-button-mini xhs-border-radius50 xhs-border-pink"
                  style="width: 150rpx; margin-right: 20rpx"
                >
                  <text style="color: #e22e4d" class="gui-icons xhs-font24"
                    >关注
                  </text>
                </view>
              </text>
            </view>
          </view>
        </view>

        <!-- 加载组件 -->
        <gui-loadmore
          ref="loadmorecom"
          :status="1"
          style="padding-bottom: 30rpx"
        ></gui-loadmore>
      </view>
    </template>
  </gui-page>
</template>
<script>
import graceJS from "@/Grace6/js/grace.js";
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  data() {
    return {
      userList: [],
      apiLoadingStatus: false,
      page: 1,
      loadMoreTimer: null,
      searchStr: "",
      navType: null,
      accessToken: "",
      userId: "",
    };
  },
  methods: {
    goCard(e) {
      console.log(e);
      if (e.userId == this.userId) {
        switch (uni.getSystemInfoSync().platform) {
          case "android":
            let ddd = {
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/my?authorId=${info.authorId}&userId=${this.userId}&token=${uni.getStorageSync(
                "token",
              )}`,
            };
            let d = JSON.stringify(ddd);
            console.log(d, "都是对的");
            window.AndroidBridge.myHomepage(d);
            console.log("运行Android上");
            break;
          case "ios":
            window.webkit.messageHandlers.myHomepage.postMessage({
              hideNavBar: "1",
              hideTotalNavBar: "1",
              hideBottomSafeBar: "1",
              url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/my?authorId=${info.authorId}&userId=${this.userId}&token=${uni.getStorageSync("token")}`,
            });
            break;
          default:
            console.log("运行在开发者工具上");
            break;
        }
      } else {
        uni.navigateTo({
          url: `/pages/card/card?authorId=${e.userId}&accessToken=${this.accessToken}&userId=${this.userId}`,
        });
      }
    },
    goBack() {
      if (this.navType) {
        uni.navigateBack();
      } else {
        // 尝试使用原生桥接方法
        try {
          if (
            uni.getSystemInfoSync().platform === "android" &&
            window.AndroidBridge
          ) {
            window.AndroidBridge.backEvent();
          } else if (
            uni.getSystemInfoSync().platform === "ios" &&
            window.webkit &&
            window.webkit.messageHandlers
          ) {
            window.webkit.messageHandlers.backEvent.postMessage({});
          } else {
            // 如果不是原生环境或原生方法不可用，使用uni-app返回
            uni.navigateBack();
          }
        } catch (e) {
          console.error("返回出错：", e);
          // 出错时也尝试使用uni-app返回
          uni.navigateBack();
        }
      }
    },
    confirm(e) {
      console.log(e);
      this.page = 1;
      this.userList = [];
      this.addHistory();
      this.getUsers();
    },
    // 监听输入
    inputting: function (e) {
      console.log(e);
      this.searchStr = e;
    },
    getUsers(isReload) {
      this.apiLoadingStatus = true;
      const that = this;
      uni.app.post(
        "/blog/author/getAuthorList",
        {
          limit: 10,
          offset: this.page,
          keyword: this.searchStr,
          authorId: uni.getStorageSync("userId"),
        },
        "",
        "",
        (res) => {
          if (res.code == 2000) {
            console.log("getUsers当前页" + that.page);
            console.log("总页数" + res.data.pages);
            if (that.page <= res.data.pages) {
              let users = res.data.records;

              if (this.page == 1) {
                this.userList = users;
              } else {
                this.userList = [...this.userList, ...users];
              }

              if (that.page == res.data.pages) {
                this.$refs.loadmorecom.nomore();
              } else {
                that.page++;
                this.$refs.loadmorecom.stoploadmore();
              }
              that.apiLoadingStatus = false;
            } else if (res.data.pages == 0) {
              this.$refs.loadmorecom.nomore();
              that.apiLoadingStatus = false;
            }
            if (isReload) {
              uni.stopPullDownRefresh();
            }
          }
        },
      );
    },
    cancelfollowAuthor(author) {
      uni.app.post(
        "/blog/action/cancelFollowAuthor",
        {
          authorId: uni.getStorageSync("userId"),
          followAuthorId: author.userId,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            author.isFollow = false;
          }
        },
      );
    },
    followAuthor(author) {
      uni.app.post(
        "/blog/action/followAuthor",
        {
          authorId: uni.getStorageSync("userId"),
          followAuthorId: author.userId,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            author.isFollow = true;
          }
        },
      );
    },
    addHistory() {
      if (uni.app.isEmpty(this.searchStr)) {
        return;
      }
      uni.app.post(
        "/blog/note/addHistory",
        { authorId: uni.getStorageSync("userId"), content: this.searchStr },
        "json",
        "",
        (res) => {},
      );
    },
  },
  //下拉刷新
  onPullDownRefresh: function () {
    if (this.apiLoadingStatus) {
      uni.stopPullDownRefresh();
      return;
    }
    this.page = 1;
    this.userList = [];
    this.getUsers(true);
  },
  onLoad: function (e) {
    this.navType = e.type;
    this.accessToken = e.accessToken;
    this.userId = e.userId;
    // 页面加载时第一次加载数据
    this.$nextTick(() => {
      this.searchStr = e.searchStr;
      this.addHistory();
      this.getUsers();
    });
  },
  onReachBottom: function () {
    if (this.apiLoadingStatus) {
      return;
    }
    // 保证触底只执行一次加载
    if (this.loadMoreTimer != null) {
      clearTimeout(this.loadMoreTimer);
    }
    this.loadMoreTimer = setTimeout(() => {
      var status = this.$refs.loadmorecom.loadMoreStatus;
      if (status != 0) {
        return null;
      }
      this.$refs.loadmorecom.loading();
      // 此处开启加载动画执行加载数据的函数
      this.getUsers();
    }, 50);
  },
};
</script>
<style scoped></style>
